package handler

import (
	"gin/cache"
	"gin/model"
	"gin/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	var user model.User
	redis_key := "user_error_" + username
	errorCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errorCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账户已冻结",
		})
		return
	}
	if err := model.DB.Where("username = ?", username).Limit(1).Find(&user).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询用户失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if pkg.Md5(user.Password) != password {
		cache.Rdb.Incr(cache.Ctx, redis_key).Err()
		if errorCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次,账号封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
			"data": user,
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}
func RoleAddNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	if rid == 0 || nid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserDetail(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var role model.Role
	model.DB.Table("roles").
		Select("user_roles.uid AS Uid", "user_roles.rid AS Rid",
			"roles.role_name AS role_name").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
}
func RoleDetail(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var node model.Node
	model.DB.Table("nodes").
		Select("role_nodes.rid AS Rid", "role_nodes.nid AS Nid",
			"nodes.node_name AS node_name").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid = ?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
}
